package cn.kgc.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author YC
 */
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        // 获取管道
        channel.pipeline()
                // 添加HTTP编解码器，用于处理HTTP请求和响应的编码解码
                .addLast(new HttpServerCodec())
                // 添加ChunkedWriteHandler，用于处理大数据流，防止内存溢出
                .addLast(new ChunkedWriteHandler())
                // 添加HTTP对象聚合器，将多个http消息聚合成完整的http请求
                .addLast(new HttpObjectAggregator(64 * 1024))
                // 添加websocket处理器，用于处理websocket请求，请求路径是以/ws开头
                .addLast(new WebSocketServerProtocolHandler("/ws"))
                // 添加心跳检测器，用于检测客户端是否存活（5分钟无活动为空闲通道）
                .addLast(new IdleStateHandler(5 * 60, 5 * 60, 5 * 60))
                // 添加心跳处理器，用于移除不活跃的websocket连接
                .addLast(new HeartBeatHandler())
                // 添加自定义的websocket处理器，用于处理接收的websocket请求
                .addLast(new ChatHandler());
    }

}
